package com.jacobson.huobi.websocket

import android.text.format.DateFormat
import com.alibaba.fastjson.JSON
import com.jacobson.core.widget.logger.LoggerFactory
import com.jacobson.huobi.common.expansion.fromJson
import com.jacobson.huobi.entities.ActionEnum
import com.jacobson.huobi.entities.SymbolInfo
import com.jacobson.huobi.entities.websocket.*
import com.jacobson.huobi.utils.GZIPUtils
import org.simple.eventbus.EventBus

object WebsocketMessageDispatcher {
    private val logger = LoggerFactory.getLogger()
    fun dispatchWebsocketMessage(message: String) {
        val protocol = message.fromJson<Protocol>()
        if (protocol == null) {
            logger.w("unknown message >>> $message")
            return
        }

        if (protocol.action == 2 || protocol.action == 7 || protocol.action == 8) {
            val currentTime = DateFormat.format("yyyy-MM-dd KK:mm:ss", System.currentTimeMillis()).toString()
            logger.v("收到消息: 类型: ${protocol.action} 时间:${currentTime}  值:" + GZIPUtils.uncompress(protocol.value))
        }else {
            logger.v("收到消息: 类型: ${protocol.action}  值:${protocol.value}")
        }
        analyzeProtocol(protocol)
    }

    private fun analyzeProtocol(protocol: Protocol) {
        when (protocol.action) {
            ActionEnum.HEARTBEAT.value -> dispatch<HeartbeatAction>(protocol.value)
            ActionEnum.REFRESH_SYMBOL.value -> dispatchRefreshSymbol(protocol)
            ActionEnum.SYSTEM_STATUS.value -> dispatch<RefreshSystemStatusResp>(protocol.value)
            ActionEnum.PUSH.value -> dispatchRefreshSymbol(protocol)
            ActionEnum.SUBSCRIBE_REFRESH_SYMBOL.value -> dispatchRefreshSymbol(protocol)
            ActionEnum.COMMIT_ACCESS_TOKEN.value -> dispatchCommitAccessToken(protocol)
            else -> logger.w("protocol action is no handler: ${protocol.action}")
        }
    }

    private inline fun <reified T> dispatch(value: String) {
        EventBus.getDefault().post(value.fromJson<T>())
    }

    private fun dispatchRefreshSymbol(protocol: Protocol) {
        val data = JSON.parseArray(GZIPUtils.uncompress((protocol.value)), SymbolInfo::class.java)
        EventBus.getDefault().post(
            RefreshSymbolResp(protocol.action,"成功", data)
        )
    }

    private fun dispatchCommitAccessToken(protocol: Protocol) {
        val data = JSON.parseObject(protocol.value)
        if (data.getInteger("code") == 0){
            WebsocketManager.sendMessage(ProtocolFactory.ofSubscribe())
        }
     }
}